import java.util.ArrayList;
import java.util.List;

public class FindAnagrams {
    // leetcode 找到字符串中所有的字母异位词
    // https://leetcode.cn/problems/find-all-anagrams-in-a-string/description/?envType=study-plan-v2&envId=top-100-liked
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> ret = new ArrayList<>();
        int len1 = s.length(), len2 = p.length();
        if (len1 < len2) return ret;
        int[] hash1 = new int[26];
        int[] hash2 = new int[26];
        // count记录窗口中有效字符的个数
        int count = 0;
        for (char c : p.toCharArray()) hash2[c-'a']++;
        for (int left = 0, right = 0; right < len1; right++) {
            char c = s.charAt(right);
            if (++hash1[c-'a'] <= hash2[c-'a']) count++;
            if (right - left >= len2) {
                if (hash1[s.charAt(left)-'a']-- <= hash2[s.charAt(left++)-'a']) {
                    count--;
                }
            }
            if (count == len2) ret.add(left);
        }
        return ret;
    }
}
